package com.rocketmq.service.impl;

import com.alibaba.fastjson.JSON;
import com.rocketmq.dao.IProductMapper;
import com.rocketmq.entity.Order;
import com.rocketmq.entity.Product;
import com.rocketmq.service.IProductService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProdectServiceImpl implements IProductService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public String setStore(String name, int store) {
        Product product = new Product();
        product.setStore(store);
        product.setName(name);
        productMapper.insertProduct(product);
        redisTemplate.opsForValue().set("product_" + product.getId(), String.valueOf(store));
        return "success";
    }

    @Override
    public String getProduct() {
        List<Product> productList = productMapper.getProductList();
        return JSON.toJSONString(productList);
    }

    @Override
    public String rushToPurchase(int productId, int userId) {

        //获取缓存中的数量
        Object o = redisTemplate.opsForValue().get("product_" + productId);
        if (o == null) {
            return "该产品还没添加抢购";
        }

        int count = Integer.parseInt(String.valueOf(o));
        if (count <= 0) {
            return "商品已抢购完";
        }

        //设置redis执行命令在一个connection里面
        redisTemplate.setEnableTransactionSupport(true);
        //redis监听产品ID
        redisTemplate.watch("product_" + productId);

        redisTemplate.multi();

        redisTemplate.opsForValue().increment("product_" + productId, -1);


        List exec = redisTemplate.exec();
        if (exec != null && exec.size() > 0) {
            //发送消息
            Order order = new Order();
            order.setProductId(productId);
            order.setUserId(userId);

            rocketMQTemplate.convertAndSend("consumer_listener", order);
            System.out.println("抢到商品");

            return "您抢到该商品，请支付商品，30秒后没有支付将会取消订单";
        }


        return "您没有抢到该商品";
    }
}
